﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace App2Wpf.Views
{
    /// <summary>
    /// DrawingVisualUC.xaml 的交互逻辑
    /// </summary>
    public partial class DrawingVisualCard : UserControl,ICardUC
    {
        public int ID { get; set; }
        public nameip connectNameip { get; set; }

        public System.Net.IPAddress iPAddress;

        ViewerPlus view;
        
        //可写画布
        WriteableBitmap wBitmap;
        //画布
        RenderTargetBitmap renderTargetBitmap;

        public DrawingVisualCard(nameip serverinfo)
        {
            InitializeComponent();

            initLoading();

            connectNameip = serverinfo;
        }

        private void initLoading()
        {
            LoadingG.Visibility = Visibility.Visible;
            MiniWindow.Visibility = Visibility.Hidden;
        }

        private void Close_Button_Click(object sender, RoutedEventArgs e)
        {
            view.session.CloseSession();
            App2Wpf.ViewModels.ServiceLocator.rightWrapVM.removeCard(this);
        }

        public void StartWork()
        {
            this.iPAddress = System.Net.IPAddress.Parse(connectNameip.ip);
            view = new ViewerPlus(iPAddress, connectNameip);

            view.OnConnect += () => {
                Dispatcher.Invoke(new Action(() =>
                {
                    LoadingG.Visibility = Visibility.Collapsed;
                    MiniWindow.Visibility = Visibility.Visible;
                }));
            };
            view.onRendering += View_refreshCard2;

            Task.Run(() => view.init(iPAddress)); //for loading not wait

            //wBitmap = new  WriteableBitmap(viewWindow.session.ViewerConfiguration.RemoteDesktopWidth,
            //                viewWindow.session.ViewerConfiguration.RemoteDesktopHeight, 96, 96, PixelFormats.Bgr24, null);
            wBitmap = new WriteableBitmap(1920,
                            1080, 96, 96, PixelFormats.Bgr32, null);

      
            renderTargetBitmap = new RenderTargetBitmap(
                1920,
                1080,
                96,
                96,
                PixelFormats.Pbgra32);

            //MiniWindow.Source = wBitmap;

        }

        private void ViewWindow_refreshCard2(WriteableBitmap block, System.Windows.Int32Rect tempRect, byte[] buffer)
        {
            //无法直接使用 block 调用线程无法访问此对象，因为另一个线程拥有该对象。
            ////WriteableBitmap nblock = block.Clone();
            System.Windows.Point rectPoint = new System.Windows.Point(view.destPoint.X, view.destPoint.Y);

            App.Current.Dispatcher.Invoke(new Action(() =>
            {
                cardTitle.Text = view.VirtualDeskForm.cardTitle;
                // 调用线程无法访问此对象，因为另一个线程拥有该对象。
                WriteableBitmap nblock = new WriteableBitmap(clientFunc.BytesToBitmapImage(buffer));

                wBitmap.Lock(); //线程内对象才能锁住
                WriteableBitmapExtensions.Blit(wBitmap,
                    new System.Windows.Point(rectPoint.X, rectPoint.Y),    // 大图或者小图的目的坐标点
                    nblock,                                                  // 输入 writeablebitmap    
                    new System.Windows.Rect(0, 0, nblock.Width, nblock.Height), //// 输入 writeablebitmap 的 RECT，实际内部只取用高度和宽度
                    Colors.White,
                    WriteableBitmapExtensions.BlendMode.None);
                wBitmap.AddDirtyRect(tempRect); //在图像未锁定时无法调用此方法

                wBitmap.Unlock();
                MiniWindow.Source = wBitmap;
            }));
        }

        // 创建一个DrawingVisual对象
        private DrawingVisual _drawingVisual = new DrawingVisual();
        // 创建Image控件用于显示图像
        private Image _image = new Image();

        private void View_refreshCard2(WriteableBitmap block, System.Windows.Int32Rect tempRect, byte[] buffer)
        {
            // 模拟接收到图片流的方法
            // 实际情况下需要通过网络或其他方式接收图片流

            // 这里使用Bitmap对象作为示例，实际情况下可以根据实际需求修改

            App.Current.Dispatcher.Invoke(new Action(() => {
                cardTitle.Text = view.VirtualDeskForm.cardTitle;
                // 将Bitmap对象转换为BitmapSource对象
                BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                view.frame.GetHbitmap(),
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            // 在DrawingVisual中绘制图像
            using (DrawingContext drawingContext = _drawingVisual.RenderOpen())
            {
                drawingContext.DrawImage(bitmapSource, new Rect(view.destPoint.X, view.destPoint.Y, bitmapSource.PixelWidth, bitmapSource.PixelHeight));
            }
            
            renderTargetBitmap.Render(_drawingVisual);

            // 将RenderTargetBitmap设置为Image控件的Source属性，实现实时显示
            MiniWindow.Source = renderTargetBitmap;

            }));
            // 释放资源
            //view.frame.Dispose();
            //bitmapSource.Freeze();
        }
    }
}
